<template>
  <view class="container">
    <!-- 表单组件 -->
    <view class="form-wrapper">
      <u-form :model="form" ref="uForm" label-width="140rpx">
        <u-form-item label="宠物名称" prop="name">
          <u-input v-model="form.name" placeholder="请输入宠物名称" />
        </u-form-item>
        <u-form-item label="宠物年龄" prop="age">
          <u-input v-model="form.age" placeholder="请输入宠物年龄"/>
        </u-form-item>
		<u-form-item label="宠物性别" prop="sex">
		  <u-radio-group v-model="form.sex">
			<u-radio name="1">弟弟</u-radio>
			<u-radio name="2">妹妹</u-radio>
		  </u-radio-group>
		</u-form-item>
        <u-form-item label="宠物生日" prop="birthday">
          <u-input v-model="form.birthday" placeholder="请选择宠物生日" @click="showCalendar=true" disabled="true"/>
		  <u-calendar v-model="showCalendar" mode="date" @change="changeCalendar"></u-calendar>
        </u-form-item>
        <u-form-item label="宠物品种" prop="breed">
          <u-input v-model="form.breed" placeholder="请输入宠物品种"/>
        </u-form-item>
        <u-form-item label="宠物颜色" prop="color">
          <u-input v-model="form.color" placeholder="请输入宠物颜色"/>
        </u-form-item>
        <u-form-item label="宠物体重" prop="weight">
          <u-input v-model="form.weight" placeholder="请输入宠物体重(单位:kg)"/>
        </u-form-item>
		<u-form-item label="是否绝育" prop="is_jy">
		  <u-radio-group v-model="form.is_jy">
			<u-radio name="0">未绝育</u-radio>
			<u-radio name="1">已绝育</u-radio>
		  </u-radio-group>
		</u-form-item>
		<u-form-item label="宠物照片" prop="imagesIds">
		</u-form-item>
		<u-form-item>
		  <!-- 图片列表 -->
		  <view class="image-list">
		    <view class="image-preview" v-for="(image) in imageList" :key="imageIndex">
		      <text class="image-delete iconfont icon-shanchu" @click="deleteImage(index)"></text>
		      <image class="image" mode="aspectFill" :src="image.path"></image>
		    </view>
		    <view v-if="!imageList || imageList.length < maxImageLength" class="image-picker"
		      @click="chooseImage(index)">
		      <text class="choose-icon iconfont icon-camera"></text>
		      <text class="choose-text">上传图片</text>
		    </view>
		  </view>
		</u-form-item>
        <u-form-item label="备注" prop="remark">
          <u-input v-model="form.remark" placeholder="请输入备注"/>
        </u-form-item>
      </u-form>
    </view>
    <!-- 操作按钮 -->
    <view class="footer">
      <view class="btn-wrapper">
        <view class="btn-item btn-item-main" :class="{ disabled }" @click="handleSubmit()">保存</view>
      </view>
    </view>
  </view>
</template>

<script>
  import SelectRegion from '@/components/select-region/select-region'
  import { isMobile } from '@/utils/verify'
  import * as PetApi from '@/api/pet'
  import * as UploadApi from '@/api/upload'

  const maxImageLength = 6

  // 表单字段元素
  const form = {
    name: '',
    sex: 1,
    birthday: '',
    color: '',
    remark: '',
    breed: '',
    is_jy: 0,
	imagesIds: [],
	weight: 0,
    age: 0
  }

  // 表单验证规则
  const rules = {
    name: [{
      required: true,
      message: '请输入宠物名称',
      trigger: ['blur', 'change']
    }],
    age: [{
      required: true,
      message: '请输入宠物年龄',
      trigger: ['blur', 'change']
    }],
    color: [{
      required: true,
      message: '请输入宠物颜色',
      trigger: ['blur', 'change']
    }],
    birday: [{
      required: true,
      message: '请输入宠物生日',
      trigger: ['blur', 'change']
    }],
    breed: [{
      required: true,
      message: '请输入宠物品种',
      trigger: ['blur', 'change']
    }],
    weight: [{
      required: true,
      message: '请输入宠物体重',
      trigger: ['blur', 'change']
    }],
  }

  export default {
    components: {
      SelectRegion
    },
    data() {
      return {
        form,
	    imageList: [],
        rules,
		showCalendar: false,
        // 最大图片数量
        maxImageLength,
        // 按钮禁用
        disabled: false
      }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {},

    // 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
    onReady() {
      this.$refs.uForm.setRules(this.rules)
    },

    methods: {
		changeCalendar(e) {
			this.form.birthday = e.result;
		},
	  // 选择图片
      chooseImage(index) {
        const app = this
        const oldImageList = app.imageList
		// console.log(app)
        // 选择图片
        uni.chooseImage({
          count: maxImageLength - oldImageList.length,
          sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
          success({ tempFiles }) {
            // tempFiles = [{path:'xxx', size:100}]
            app.imageList = oldImageList.concat(tempFiles)
		    console.log(app.imageList)
          }
        });
      },

      // 删除图片
      deleteImage(index) {
        this.imageList.splice(index, 1)
        this.form.imagesIds.splice(index, 1)
		console.log(this.imageList)
		console.log(this.form.imagesIds)
      },
	  
	  // 表单提交
	  handleSubmit() {
	    const app = this
	    if (app.disabled) {
	      return false
	    }
	    app.$refs.uForm.validate(valid => {
	      if (valid) {
	  			app.disabled = true
	  			// 判断是否需要上传图片
	  			const imagesLength = app.getImagesLength()
	  			if (imagesLength > 0) {
	  			  app.uploadFile()
	  			    .then(() => {
	  					console.log('commit')
	  			      app.onSubmit()
	  			    })
	  			    .catch(err => {
	  			      app.disabled = false
	  			      if (err.statusCode !== 0) {
	  			        app.$toast(err.errMsg)
	  			      }
	  			    })
	  			} else {
					app.onSubmit()
	  			  // app.disabled = false
	  			  // app.$toast('请先上传图片')
	  			}
	      }
	    })
	  },
	  
	  onSubmit() {
	  	const app = this
	    PetApi.add(app.form)
		  .then(result => {
		    app.$toast(result.message)
		    setTimeout(() => {
		      uni.navigateBack()
		    }, 1500)
		  })
		  .finally(() => app.disabled = false)
	  },
	  
	  // 统计图片数量
	  getImagesLength() {
	    let imagesLength = this.imageList.length
	    return imagesLength
	  },
	  
	  // 上传图片
	  uploadFile() {
	    const app = this
	    const { form } = app
	    // 整理上传文件路径
	    const files = []
	    
	    // console.log(form)
	    if (app.imageList.length) {
	      // const images = app.imageList.map(image => image)
	      const images = app.imageList.map((item,index,arr)=>{
	  			  // if(!item.size){
	  			  console.log(item)
	  			  console.log(typeof(item.size))
	  			  if(typeof(item.size) == 'undefined'){
	  				  console.log('bucunz')
	  				  return null
	  			  }
	  			  let data = {}
	  			  data.path = item.path
	  			  data.size = item.size
	  			  return data
	  		  })
	  		  console.log(images)
	  		  for(var i = 0; i < images.length; i++) {
	  		      if(!images[i]) {
	  		          images.splice(i,1);
	  		          i = i - 1; // i - 1 ,因为空元素在数组下标 2 位置，删除空之后，后面的元素要向前补位
	  		      }
	  		  }
	  		  // images = images2
	  		  console.log(images)
	  		  if(images.length){
	  			  console.log(1)
	  			files.push({ images })
	  		  }
	  		  console.log(2)
	    }
	  		console.log(files)
	    // 批量上传
	    return new Promise((resolve, reject) => {
	      Promise.all(files.map((file, index) => {
			  return new Promise((resolve, reject) => {
				UploadApi.image(file.images)
				  .then(fileIds => {
					console.log(app.form.imagesIds)
					app.form.imagesIds = app.form.imagesIds.concat(fileIds)
					console.log(app.form.imagesIds)
					resolve(fileIds)
				  })
				  .catch(reject=>{
								  console.log(reject)
							  })
			  })
	        }))
	        .then(resolve, reject)
	    })
	  }
    }
  }
</script>

<style>
  page {
    background: #f7f8fa;
  }
</style>
<style lang="scss" scoped>
  .page-title {
    width: 94%;
    margin: 0 auto;
    padding-top: 40rpx;
    font-size: 28rpx;
    color: rgba(69, 90, 100, 0.6);
  }

  .form-wrapper {
    margin: 20rpx auto 20rpx auto;
    padding: 0 40rpx;
    width: 94%;
    box-shadow: 0 1rpx 5rpx 0px rgba(0, 0, 0, 0.05);
    border-radius: 16rpx;
    background: #fff;
  }

  /* 底部操作栏 */

  .footer {
    margin-top: 60rpx;

    .btn-wrapper {
      height: 100%;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
    }

    .btn-item {
      flex: 1;
      font-size: 28rpx;
      height: 100rpx;
      line-height: 100rpx;
      text-align: center;
      color: #fff;
      border-radius: 50rpx;
    }

    .btn-item-main {
      background: linear-gradient(to right, #f9211c, #ff6335);

      // 禁用按钮
      &.disabled {
        background: #ff9779;
      }
    }

  }
  
  
  
  .image-list {
    padding: 0 20rpx;
    margin-top: 20rpx;
    margin-bottom: -20rpx;
  
    &:after {
      clear: both;
      content: " ";
      display: table;
    }
  
    .image {
      display: block;
      width: 100%;
      height: 100%;
    }
  
    .image-picker,
    .image-preview {
      width: 170rpx;
      height: 170rpx;
      margin-right: 30rpx;
      margin-bottom: 30rpx;
      float: left;
  
      &:nth-child(3n+0) {
        margin-right: 0;
      }
    }
  
    .image-picker {
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
      border: 1rpx dashed #ccc;
      color: #ccc;
  
      .choose-icon {
        font-size: 48rpx;
        margin-bottom: 6rpx;
      }
  
      .choose-text {
        font-size: 24rpx;
      }
    }
  
    .image-preview {
      position: relative;
  
      .image-delete {
        position: absolute;
        top: -15rpx;
        right: -15rpx;
        height: 42rpx;
        width: 42rpx;
        line-height: 42rpx;
        background: rgba(0, 0, 0, 0.64);
        border-radius: 50%;
        color: #fff;
        font-weight: bolder;
        font-size: 22rpx;
        z-index: 10;
        text-align: center;
      }
    }
  }
</style>
